// 全局变量
let service;
let activeSheetId = '';
let activeSheet = '';
let sheetIds = [];

// 服务初始化
let googleSheetsService;
if (typeof require !== 'undefined') {
    // Node.js 环境
    service = require('./google-sheets-service-require.js');
    googleSheetsService = service;
} else {
    // 浏览器环境
    service = window.GoogleSheetsService;
    // googleSheetsService 将在 DOM 加载完成后由 google-sheets-service-browser.js 初始化
}

// DOM 加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    setupWindowControls();
    loadSheetIds(); // 初始化时加载 sheet IDs
    
    // 在浏览器环境中初始化 googleSheetsService
    if (typeof require === 'undefined') {
        // 确保 google-sheets-service-browser.js 已经加载并初始化了 window.GoogleSheetsService
        if (window.GoogleSheetsService) {
            googleSheetsService = window.GoogleSheetsService;
            console.log('Google Sheets service initialized from window.GoogleSheetsService');
        } else {
            console.error('window.GoogleSheetsService not available');
        }
    }
});

// Setup window controls
function setupWindowControls() {
    const minimizeBtn = document.querySelector('.minimize-btn');
    const maximizeBtn = document.querySelector('.maximize-btn');
    const closeBtn = document.querySelector('.close-btn');

    if (minimizeBtn) {
        minimizeBtn.addEventListener('click', () => {
            if (window.electronAPI && window.electronAPI.minimizeWindow) {
                window.electronAPI.minimizeWindow();
            }
        });
    }

    if (maximizeBtn) {
        maximizeBtn.addEventListener('click', () => {
            if (window.electronAPI && window.electronAPI.toggleMaximize) {
                window.electronAPI.toggleMaximize();
            }
        });
    }

    if (closeBtn) {
        closeBtn.addEventListener('click', () => {
            if (window.electronAPI && window.electronAPI.closeWindow) {
                window.electronAPI.closeWindow();
            }
        });
    }
}

// Setup event listeners
function setupEventListeners() {
    // Form input change detection for labels
    const inputs = document.querySelectorAll('.user-box input');
    inputs.forEach(input => {
        input.addEventListener('input', function() {
            if (this.value.trim() !== '') {
                this.setAttribute('data-has-value', 'true');
            } else {
                this.removeAttribute('data-has-value');
            }
            
            // Check for "closed late" status
            if (this.id === 'closureStatus' && this.value.toLowerCase() === 'closed late') {
                this.classList.add('red-text');
            } else if (this.id === 'closureStatus') {
                this.classList.remove('red-text');
            }
        });
    });

    // Enter key support for PLM Code search
    document.getElementById('plmCode').addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            e.preventDefault();
            searchCode();
        }
    });
}

// Load sheet IDs from localStorage
function loadSheetIds() {
    const savedSheetIds = localStorage.getItem('google-sheets2-sheet-ids');
    if (savedSheetIds) {
        sheetIds = JSON.parse(savedSheetIds);
    }
}

// Save sheet IDs to localStorage
function saveSheetIds() {
    localStorage.setItem('google-sheets2-sheet-ids', JSON.stringify(sheetIds));
}

// Show message toast
function showMessage(message, type = 'info', duration = 3000) {
    const toast = document.getElementById('message-toast');
    const messageText = document.getElementById('message-text');
    
    messageText.textContent = message;
    toast.className = `message-toast ${type}`;
    toast.style.display = 'flex';
    
    if (duration > 0) {
        setTimeout(() => {
            closeMessage();
        }, duration);
    }
}

// Close message toast
function closeMessage() {
    const toast = document.getElementById('message-toast');
    toast.style.display = 'none';
}

// Show/hide loading overlay
function showLoading(text = 'Loading...') {
    const overlay = document.getElementById('loading-overlay');
    const loadingText = document.getElementById('loading-text');
    loadingText.textContent = text;
    overlay.style.display = 'flex';
}

function hideLoading() {
    const overlay = document.getElementById('loading-overlay');
    overlay.style.display = 'none';
}

// Settings functions
function openSettings() {
    const panel = document.getElementById('settings-panel');
    panel.style.display = 'block';
    loadSheetIds(); // 确保在渲染前加载数据
    renderSheetList();
}

function closeSettings() {
    const panel = document.getElementById('settings-panel');
    panel.style.display = 'none';
}

function renderSheetList() {
    const sheetList = document.getElementById('sheet-list');
    sheetList.innerHTML = '';
    
    sheetIds.forEach((sheetId, index) => {
        const sheetItem = document.createElement('div');
        sheetItem.className = 'sheet-item';
        sheetItem.innerHTML = `
            <input type="text" value="${sheetId}" onchange="updateSheetId(${index}, this.value)" placeholder="输入Sheet ID">
            <button onclick="removeSheet(${index})">删除</button>
        `;
        sheetList.appendChild(sheetItem);
    });
}

function addSheet() {
    sheetIds.push('');
    renderSheetList();
}

function removeSheet(index) {
    sheetIds.splice(index, 1);
    renderSheetList();
}

function updateSheetId(index, value) {
    sheetIds[index] = value;
}

function saveSettings() {
    try {
        // Filter out empty sheet IDs
        const validIds = sheetIds.filter(id => id.trim() !== '');
        sheetIds = validIds;
        saveSheetIds();
        showMessage('Save Successfully!', 'success');
        closeSettings();
    } catch (error) {
        console.error('Save failed:', error);
        showMessage('Save failed!', 'error');
    }
}

// Search PLM Code
// 全局变量存储搜索结果
let searchResults = [];

// 检查sheet名称是否为纯数字
function isNumericSheetName(sheetName) {
    return /^\d+$/.test(sheetName.trim());
}

async function searchCode() {
    const plmCodeInput = document.getElementById('plmCode');
    const plmCode = plmCodeInput.value.trim();
    
    if (plmCode === '') {
        showMessage('Please enter PLM Code', 'error');
        return;
    }
    
    if (sheetIds.length === 0) {
        showMessage('Please set Sheet ID first.', 'error');
        return;
    }
    
    // 检查服务是否可用
    if (!googleSheetsService) {
        showMessage('Google Sheets service not available. Please check the configuration.', 'error');
        console.error('googleSheetsService is null');
        return;
    }
    
    showLoading('Searching all numeric sheets...');
    
    // 清空之前的搜索结果
    searchResults = [];
    
    try {
        for (const sheetId of sheetIds) {
            if (sheetId.trim() !== '') {
                // Get sheet names - 使用本地服务
                const sheetNames = await googleSheetsService.getSheetNames(sheetId);
                
                for (const sheet of sheetNames) {
                    // 只搜索纯数字名称的sheet
                    if (isNumericSheetName(sheet)) {
                        console.log('Searching in numeric sheet:', sheet);
                        
                        // Read row data - 使用本地服务
                        const data = await googleSheetsService.readRowData(sheetId, `${sheet}!A1:Z1000`);
                        
                        // 查找所有匹配的行，而不是只找第一个
                        for (let i = 0; i < data.length; i++) {
                            const row = data[i];
                            if (row[5] === plmCode) { // F column is index 5
                                searchResults.push({
                                    sheetId: sheetId,
                                    sheetName: sheet,
                                    rowIndex: i + 1, // 1-based index
                                    rowData: row
                                });
                            }
                        }
                    } else {
                        console.log('Skipping non-numeric sheet:', sheet);
                    }
                }
            }
        }
        
        hideLoading();
        
        if (searchResults.length > 0) {
            // 显示第一个结果的数据
            const firstResult = searchResults[0];
            activeSheetId = firstResult.sheetId;
            activeSheet = firstResult.sheetName;
            
            // Fill form data with first result
            const match = firstResult.rowData;
            document.getElementById('tcfType').value = match[2] || ''; // C column is index 2
            document.getElementById('sampleReceivedDate').value = match[8] || ''; // I column is index 8
            document.getElementById('reviewFromDate').value = match[10] || ''; // K column is index 10
            document.getElementById('validateDate').value = match[11] || ''; // L column is index 11
            document.getElementById('closeDate').value = match[15] || ''; // P column is index 15
            document.getElementById('statusUpdate').value = match[13] || ''; // N column is index 13
            document.getElementById('closureStatus').value = match[18] || ''; // S column is index 18
            
            // Trigger input events to update labels
            const inputs = document.querySelectorAll('.user-box input');
            inputs.forEach(input => {
                if (input.value.trim() !== '') {
                    input.setAttribute('data-has-value', 'true');
                }
                // Check for red text
                if (input.id === 'closureStatus' && input.value.toLowerCase() === 'closed late') {
                    input.classList.add('red-text');
                }
            });
            
            // 显示搜索结果摘要
            let resultMessage = `Found ${searchResults.length} record(s):\n`;
            searchResults.forEach((result, index) => {
                resultMessage += `${index + 1}. Sheet: ${result.sheetName} (Row ${result.rowIndex})\n`;
            });
            
            showSearchResults(resultMessage);
            showMessage(`Found ${searchResults.length} record(s)! Showing first result.`, 'success');
            
            // 根据搜索结果数量动态改变按钮
            updateEntryButton();
            
        } else {
            showSearchResults('No records found.');
            showMessage('No records found.', 'error');
            // 重置按钮为默认状态
            resetEntryButton();
        }
        
    } catch (error) {
        hideLoading();
        showSearchResults('Reading data failed, please try again.');
        showMessage('Reading data failed, please try again.', 'error');
        console.error(error);
        // 重置按钮为默认状态
        resetEntryButton();
    }
}

// 根据搜索结果数量动态更新ENTRY按钮
function updateEntryButton() {
    const entryBtn = document.querySelector('a[onclick="handleEntry(event)"]');
    if (entryBtn && searchResults.length > 1) {
        // 多个结果时，改为批量更新按钮
        entryBtn.innerHTML = 'BATCH UPDATE ALL<span></span>';
        entryBtn.className = 'batch-update-btn';
        entryBtn.onclick = function(event) {
            event.preventDefault();
            batchUpdateAllResults();
        };
    } else if (entryBtn) {
        // 单个结果或默认状态，保持原有功能
        entryBtn.innerHTML = 'ENTRY<span></span>';
        entryBtn.className = '';
        entryBtn.onclick = function(event) {
            handleEntry(event);
        };
    }
}

// 重置ENTRY按钮为默认状态
function resetEntryButton() {
    const entryBtn = document.querySelector('a[onclick="handleEntry(event)"], .batch-update-btn');
    if (entryBtn) {
        entryBtn.innerHTML = 'ENTRY<span></span>';
        entryBtn.className = '';
        entryBtn.onclick = function(event) {
            handleEntry(event);
        };
    }
}

// 批量更新所有搜索结果
async function batchUpdateAllResults() {
    if (searchResults.length === 0) {
        showMessage('No search results to update', 'error');
        return;
    }
    
    const plmCode = document.getElementById('plmCode').value.trim();
    
    try {
        // 使用本地服务获取用户设置
        const userSettings = await googleSheetsService.getUserSettings();
        
        // Check user settings
        if (!userSettings.email || !userSettings.site) {
            showMessage('Please configure user email and site in Settings first!', 'error');
            return;
        }
        
        // 获取原始日期值
        const rawSampleDate = document.getElementById('sampleReceivedDate').value;
        const rawReviewDate = document.getElementById('reviewFromDate').value;
        const rawValidateDate = document.getElementById('validateDate').value;
        const rawCloseDate = document.getElementById('closeDate').value;
        
        // 格式化日期
        const formattedSampleDate = formatDate(rawSampleDate);
        const formattedReviewDate = formatDate(rawReviewDate);
        const formattedValidateDate = formatDate(rawValidateDate);
        const formattedCloseDate = formatDate(rawCloseDate);
        
        const updates = {
            2: document.getElementById('tcfType').value,
            5: plmCode,
            8: formattedSampleDate,
            10: formattedReviewDate,
            11: formattedValidateDate,
            13: document.getElementById('statusUpdate').value,
            15: formattedCloseDate
        };
        
        showLoading(`Updating ${searchResults.length} records...`);
        
        let successCount = 0;
        let errorCount = 0;
        
        for (const result of searchResults) {
            try {
                // 使用本地服务更新每个结果
                await googleSheetsService.updatePartialColumns(
                    result.sheetId,
                    result.sheetName,
                    plmCode,
                    updates,
                    `${result.sheetName}!A1:Z1000`
                );
                successCount++;
                console.log(`Updated record in ${result.sheetName} row ${result.rowIndex}`);
            } catch (error) {
                errorCount++;
                console.error(`Failed to update record in ${result.sheetName} row ${result.rowIndex}:`, error);
            }
        }
        
        // 准备监控数据
        const data = [{
            user_name: userSettings.email.split('@')[0],
            user_location: userSettings.site,
            rpa_id: "137",
            rpa_name: "Google Sheets Entry",
            rpa_version: "1.0.2",
            occurrence: new Date().toLocaleString('en-US', {
                weekday: 'short',
                day: '2-digit',
                month: 'short',
                year: 'numeric',
                hour: '2-digit',
                minute: '2-digit',
                second: '2-digit',
                hour12: false
            }),
            info: `Google Sheets批量数据更新 - 成功: ${successCount}, 失败: ${errorCount}`,
            extra: plmCode
        }];
        
        try {
            // 使用本地服务发送监控数据
            await googleSheetsService.sendMonitoringData(data);
            console.log('渲染进程：批量更新监控数据发送成功');
        } catch (error) {
            console.error('渲染进程：批量更新监控数据发送失败:', error);
        }
        
        hideLoading();
        
        if (errorCount === 0) {
            showMessage(`Successfully updated all ${successCount} records!`, 'success');
        } else {
            showMessage(`Updated ${successCount} records, ${errorCount} failed.`, 'warning');
        }
        
    } catch (error) {
        hideLoading();
        showMessage('Batch update failed, please try again.', 'error');
        console.error('Batch update error:', error);
    }
}

function showSearchResults(message) {
    const resultsDiv = document.getElementById('search-results');
    const resultsText = document.getElementById('search-results-text');
    
    resultsText.textContent = message;
    resultsDiv.style.display = 'block';
}

// Save entry data
async function saveEntry() {
    const plmCode = document.getElementById('plmCode').value.trim();
    
    // 获取原始日期值
    const rawSampleDate = document.getElementById('sampleReceivedDate').value;
    const rawReviewDate = document.getElementById('reviewFromDate').value;
    const rawValidateDate = document.getElementById('validateDate').value;
    const rawCloseDate = document.getElementById('closeDate').value;
    
    // 格式化日期并记录调试信息
    const formattedSampleDate = formatDate(rawSampleDate);
    const formattedReviewDate = formatDate(rawReviewDate);
    const formattedValidateDate = formatDate(rawValidateDate);
    const formattedCloseDate = formatDate(rawCloseDate);
    
    console.log('日期格式化调试信息:');
    console.log('Sample Date:', rawSampleDate, '->', formattedSampleDate);
    console.log('Review Date:', rawReviewDate, '->', formattedReviewDate);
    console.log('Validate Date:', rawValidateDate, '->', formattedValidateDate);
    console.log('Close Date:', rawCloseDate, '->', formattedCloseDate);
    
    const updates = {
        2: document.getElementById('tcfType').value,
        5: plmCode,
        8: formattedSampleDate,
        10: formattedReviewDate,
        11: formattedValidateDate,
        13: document.getElementById('statusUpdate').value,
        15: formattedCloseDate
    };
    
    console.log('最终更新数据:', updates);

    // 使用本地服务
    await googleSheetsService.updatePartialColumns(
        activeSheetId,
        activeSheet,
        plmCode,
        updates,
        `${activeSheet}!A1:Z1000`
    );
}

// Handle entry submission
async function handleEntry(event) {
    event.preventDefault();
    
    const plmCode = document.getElementById('plmCode').value.trim();
    const searchResults = document.getElementById('search-results');
    
    // Check if PLM Code has been searched
    if (!plmCode || searchResults.style.display === 'none') {
        showMessage('Please search PLM Code first...', 'warning');
        return;
    }
    
    try {
        // 使用本地服务获取用户设置
        const userSettings = await googleSheetsService.getUserSettings();
        
        // Check user settings
        if (!userSettings.email || !userSettings.site) {
            showMessage('Please configure user email and site in Settings first!', 'error');
            return;
        }
        
        showLoading('Updating Data, please wait...');
        
        // Save entry data
        await saveEntry();
        
        // Prepare monitoring data
        const data = [{
            user_name: userSettings.email.split('@')[0],
            user_location: userSettings.site,
            rpa_id: "137",
            rpa_name: "Google Sheets Entry",
            rpa_version: "1.0.2",
            occurrence: new Date().toLocaleString('en-US', {
                weekday: 'short',
                day: '2-digit',
                month: 'short',
                year: 'numeric',
                hour: '2-digit',
                minute: '2-digit',
                second: '2-digit',
                hour12: false
            }),
            info: "Google Sheets数据更新",
            extra: plmCode
        }];
        
        try {
            // 使用本地服务发送监控数据
            await googleSheetsService.sendMonitoringData(data);
            console.log('渲染进程：发送监控数据成功');
        } catch (error) {
            console.error('渲染进程：发送监控数据失败:', error);
        }
        
        hideLoading();
        showMessage('Update Successfully!', 'success', 0); // 0 means no auto-close
        
    } catch (error) {
        hideLoading();
        showMessage('Update Failed!', 'error');
        console.error('Update Failed:', error);
    }
}

// Format date function for Google Sheets
function formatDate(date) {
    if (!date) return '';
    
    // 尝试解析美式日期格式 (MM/DD/YYYY 或 M/D/YYYY)
    const dateRegex = /^(\d{1,2})\/(\d{1,2})\/(\d{4})$/;
    const match = date.match(dateRegex);
    
    if (match) {
        const [, month, day, year] = match;
        // 创建标准日期对象
        const d = new Date(year, month - 1, day);
        
        // 验证日期是否有效
        if (d.getFullYear() == year && d.getMonth() == month - 1 && d.getDate() == day) {
            // 返回 Excel/Google Sheets 序列号格式
            // Excel 日期序列号：从1900年1月1日开始的天数
            const excelEpoch = new Date(1899, 11, 30); // Excel 的基准日期
            const timeDiff = d.getTime() - excelEpoch.getTime();
            const daysDiff = Math.floor(timeDiff / (1000 * 60 * 60 * 24));
            
            console.log(`日期转换: ${date} -> ${d.toISOString()} -> Excel序列号: ${daysDiff}`);
            return daysDiff;
        }
    }
    
    // 如果不是预期格式，尝试直接解析
    try {
        const d = new Date(date);
        if (!isNaN(d.getTime())) {
            // 返回 Excel 序列号
            const excelEpoch = new Date(1899, 11, 30);
            const timeDiff = d.getTime() - excelEpoch.getTime();
            const daysDiff = Math.floor(timeDiff / (1000 * 60 * 60 * 24));
            
            console.log(`日期转换(备用): ${date} -> ${d.toISOString()} -> Excel序列号: ${daysDiff}`);
            return daysDiff;
        }
    } catch (e) {
        console.warn('无法解析日期格式:', date);
    }
    
    // 如果都失败了，返回原始值
    return date;
}

// Cleanup function
window.addEventListener('beforeunload', function() {
    // 清理资源
});

// Add CSS for data-has-value attribute
const style = document.createElement('style');
style.textContent = `
    .user-box input[data-has-value="true"] ~ label {
        top: -20px;
        left: 0;
        color: #bdb8b8;
        font-size: 12px;
    }
`;
document.head.appendChild(style);